package com.study.talk.app.chat;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;


import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.PickVisualMediaRequest;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.study.talk.R;
import com.study.talk.adapter.GroupChatMessageListAdapter;
import com.study.talk.app.base.BaseActivity;
import com.study.talk.app.group.GroupInfoActivity;
import com.study.talk.app.group.InviteFriendJoinGroupActivity;
import com.study.talk.databinding.ActivityGroupChatBinding;
import com.study.talk.entity.GroupInfo;
import com.study.talk.entity.GroupMessageRecord;
import com.study.talk.net.NetApi;
import com.study.talk.netty.NettyClient;
import com.study.talk.netty.message.request.GroupMessageRequest;
import com.study.talk.netty.message.response.MessageSelfResponse;
import com.study.talk.util.AppExecutor;
import com.study.talk.util.DateUtil;
import com.study.talk.util.FileUtil;
import com.study.talk.util.GsonInstance;
import com.study.talk.util.ToastUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

public class GroupChatActivity extends BaseActivity implements View.OnClickListener {


    private GroupInfo groupInfo;

    private List<GroupMessageRecord> messageRecordList;

    private GroupChatMessageListAdapter adapter;

    private ActivityResultLauncher<PickVisualMediaRequest> selectPhoto;
    private ActivityResultLauncher<Uri> takePhoto;

    private LinearLayoutManager linearLayoutManager;

    private final String TAG = "GroupChatActivity";

    private ActivityGroupChatBinding activityGroupChatBinding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityGroupChatBinding = ActivityGroupChatBinding.inflate(getLayoutInflater());
        setContentView(activityGroupChatBinding.getRoot());
        setSupportActionBar(activityGroupChatBinding.groupChatToolbar);
        groupInfo = GsonInstance.instance.fromJson(getIntent().getStringExtra("data"), GroupInfo.class);

        selectPhoto = registerForActivityResult(new ActivityResultContracts.PickVisualMedia(), uri -> {
            if (uri != null) {
                uploadImage(FileUtil.getPathFromUri(GroupChatActivity.this, uri));
            }
        });
        takePhoto = registerForActivityResult(new ActivityResultContracts.TakePicture(), result -> {
            if (result) {
                uploadImage(FileUtil.getPathFromUri(GroupChatActivity.this, uri));
            }
        });
        initView();
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.group_chat_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    public void toBottom() {
        linearLayoutManager.scrollToPositionWithOffset(adapter.getItemCount() - 1, Integer.MIN_VALUE);
    }


    @SuppressLint("NonConstantResourceId")
    private void initView() {
        getSupportActionBar().setTitle(groupInfo.getName());
        activityGroupChatBinding.groupChatToolbar.setNavigationOnClickListener(v -> finish());
        activityGroupChatBinding.groupChatToolbar.setOnMenuItemClickListener(item -> {
            switch (item.getItemId()) {
                case R.id.group_chat_other_setting ->
                        ToastUtil.showToast(GroupChatActivity.this, "功能开发中...");
                case R.id.chat_group_info -> {
                    Intent intent = new Intent(GroupChatActivity.this, GroupInfoActivity.class);
                    intent.putExtra("data", GsonInstance.instance.toJson(groupInfo));
                    startActivity(intent);
                }
                case R.id.invite_friend_join_group -> {
                    Intent intent = new Intent(GroupChatActivity.this, InviteFriendJoinGroupActivity.class);
                    intent.putExtra("data", GsonInstance.instance.toJson(groupInfo));
                    startActivity(intent);
                }
            }
            //完成处理
            return true;
        });

        //点击发送消息按钮
        activityGroupChatBinding.groupChatMsgSendBt.setOnClickListener(view -> {
            if (checkInput(activityGroupChatBinding.groupChatMsgEdit, "不能发送空消息或者空格内容哦"))
                return;
            String content = editTrim(activityGroupChatBinding.groupChatMsgEdit);
            GroupMessageRequest messageRequest = new GroupMessageRequest(groupInfo.getId(), content, 0);
            messageRequest.setDateTime(DateUtil.getCurrentTime());
            NettyClient.sendMessage(messageRequest);
            showLoadingDialog();
        });

        setData();


        activityGroupChatBinding.groupChatBottomMenuAudio.setOnClickListener(this);
        activityGroupChatBinding.groupChatBottomMenuEmoji.setOnClickListener(this);
        activityGroupChatBinding.groupChatBottomMenuOther.setOnClickListener(this);

        activityGroupChatBinding.groupChatBottomMenuImage.setOnClickListener(view -> showSelectPhotoDialog(selectPhoto, takePhoto));
    }

    private void setData() {
        AppExecutor.getInstance().FILE_IO().execute(() -> {
            messageRecordList = getApp().db.groupMessageDao().getListByGroupId(groupInfo.getId());
            adapter = new GroupChatMessageListAdapter(messageRecordList, this);
            AppExecutor.getInstance().MAIN_HANDLER().post(() -> {
                linearLayoutManager = new LinearLayoutManager(this);
                linearLayoutManager.setStackFromEnd(true);
                activityGroupChatBinding.groupChatListView.setLayoutManager(linearLayoutManager);
                activityGroupChatBinding.groupChatListView.setAdapter(adapter);
            });
            /*runOnUiThread(() -> {
                linearLayoutManager = new LinearLayoutManager(this);
                linearLayoutManager.setStackFromEnd(true);
                activityGroupChatBinding.groupChatListView.setLayoutManager(linearLayoutManager);
                activityGroupChatBinding.groupChatListView.setAdapter(adapter);
            });*/
        });
        /*new Thread(() -> {
            messageRecordList = getApp().db.groupMessageDao().getListByGroupId(groupInfo.getId());
            adapter = new GroupChatMessageListAdapter(messageRecordList, this);
            runOnUiThread(() -> {
                linearLayoutManager = new LinearLayoutManager(this);
                linearLayoutManager.setStackFromEnd(true);
                activityGroupChatBinding.groupChatListView.setLayoutManager(linearLayoutManager);
                activityGroupChatBinding.groupChatListView.setAdapter(adapter);
            });
        }).start();*/
    }

    /**
     * @description: 消息发送成功处理
     * @param: messageSelfResponse
     * @return: void
     * @author thor
     * @date: 2024/8/17 14:24
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageSelfResponse(MessageSelfResponse messageSelfResponse) {
        dismissLoadingDialog(); //取消对话框加载
        if (messageSelfResponse.getSuccess()) {
            //ToastUtil.showToast(GroupChatActivity.this, "消息发送成功"); //消息提示
            setText(activityGroupChatBinding.groupChatMsgEdit, "");  //清空输入框
            GroupMessageRecord messageRecord = new GroupMessageRecord(getApp().userInfo, messageSelfResponse, true);

            new Thread(() -> getApp().db.groupMessageDao().insertMessage(messageRecord)).start();  //创建消息并保存

            messageRecordList.add(messageRecord); //将消息加入聊天列表

            adapter.notifyItemInserted(messageRecordList.size());   //更新列表UI
            toBottom();  //将列表滑动至最低端
        } else {
            ToastUtil.showToast(getApplicationContext(), messageSelfResponse.getReason());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, priority = 10)
    public void onMessageResponse(GroupMessageRecord messageRecord) {
        //new Thread(() -> getApp().db.groupMessageDao().insertMessage(messageRecord)).start();
        AppExecutor.getInstance().FILE_IO().execute(() -> getApp().db.groupMessageDao().insertMessage(messageRecord));
        messageRecordList.add(messageRecord);
        //更新列表UI显示
        adapter.notifyItemInserted(messageRecordList.size());
        toBottom();
    }


    public void uploadImage(String path) {
        NetApi.uploadImage(path, this, data -> {
            GroupMessageRequest messageRequest = new GroupMessageRequest(groupInfo.getId(), data, 1);
            messageRequest.setDateTime(DateUtil.getCurrentTime());
            NettyClient.sendMessage(messageRequest);
            runOnUiThread(this::showLoadingDialog);
        }, msg -> runOnUiThread(() -> ToastUtil.showToast(GroupChatActivity.this, msg)));
    }

    @Override
    public void onClick(View v) {
        ToastUtil.showToast(this, "功能开发中...");
    }
}